package org.example.chat;

import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.geometry.Insets;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.stage.FileChooser;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.*;

public class HelloController {
    @FXML
    private ListView<Message> messageList;
    @FXML
    private TextField messageInput;
    @FXML
    private TextField usernameInput;

    private ChatClient chatClient;
    private String username;
    private static Map<String, String> userAvatars = new HashMap<>();
    private String userAvatar;

    public void initialize() {
        chatClient = new ChatClient();
        messageList.setCellFactory(listView -> new MessageCell());
    }

    @FXML
    private void login() {
        username = usernameInput.getText();
        if (!username.isEmpty()) {
            try {
                userAvatar = getRandomAvatar();
                userAvatars.put(username, userAvatar);
                chatClient.startConnection("127.0.0.1", 12345, this::receiveMessage);
                chatClient.sendMessage("LOGIN:" + username + ":" + userAvatar);
                usernameInput.setDisable(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @FXML
    private void sendImage() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.getExtensionFilters().add(
            new FileChooser.ExtensionFilter("Image Files", "*.png", "*.jpg", "*.gif")
        );
        File file = fileChooser.showOpenDialog(null);
        
        if (file != null) {
            try {
                byte[] imageData = Files.readAllBytes(file.toPath());
                String base64Image = Base64.getEncoder().encodeToString(imageData);
                String imageMessage = "IMAGE:" + base64Image;
                chatClient.sendMessage(username + ": " + imageMessage);
                messageList.scrollTo(messageList.getItems().size() - 1);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void receiveMessage(String message) {
        Platform.runLater(() -> {
            if (message.startsWith("SYSTEM:")) {
                String content = message.substring(7);
                messageList.getItems().add(new Message("系统", content, false, null));
            } else if (message.startsWith("LOGIN:")) {
                String[] parts = message.substring(6).split(":");
                String loginUsername = parts[0];
                String avatar = parts[1];
                userAvatars.put(loginUsername, avatar);
                messageList.getItems().add(new Message("系统", loginUsername + " 加入了聊天室", false, avatar));
            } else if (message.startsWith("USER:")) {
                // 处理现有用户信息
                String[] parts = message.substring(5).split(":");
                String existingUsername = parts[0];
                String existingAvatar = parts[1];
                userAvatars.put(existingUsername, existingAvatar);
            } else {
                String[] parts = message.split(":", 2);
                String sender = parts[0];
                String content = parts[1].trim();
                String avatar = sender.equals(username) ? userAvatar : getUserAvatar(sender);
                messageList.getItems().add(new Message(sender, content, sender.equals(username), avatar));
            }
            
            messageList.scrollTo(messageList.getItems().size() - 1);
        });
    }

    @FXML
    private void sendMessage() {
        String message = messageInput.getText();
        if (!message.isEmpty() && username != null) {
            chatClient.sendMessage(username + ": " + message);
            messageInput.clear();
            messageList.scrollTo(messageList.getItems().size() - 1);
        }
    }

    private static class Message {
        final String sender;
        final String content;
        final boolean isOwn;
        final String avatar;

        Message(String sender, String content, boolean isOwn, String avatar) {
            this.sender = sender;
            this.content = content;
            this.isOwn = isOwn;
            this.avatar = avatar;
        }
    }

    private class MessageCell extends ListCell<Message> {
        @Override
        protected void updateItem(Message message, boolean empty) {
            super.updateItem(message, empty);
            if (empty || message == null) {
                setText(null);
                setGraphic(null);
            } else {
                HBox container = new HBox(15);
                container.setPadding(new Insets(10, 15, 10, 15));
                
                if (message.sender.equals("系统")) {
                    Label systemLabel = new Label(message.content);
                    systemLabel.setPadding(new Insets(10, 15, 10, 15));
                    systemLabel.setStyle("-fx-text-fill: #666666; -fx-font-size: 13px;");
                    
                    Region leftSpacer = new Region();
                    Region rightSpacer = new Region();
                    HBox.setHgrow(leftSpacer, Priority.ALWAYS);
                    HBox.setHgrow(rightSpacer, Priority.ALWAYS);
                    
                    container.getChildren().addAll(leftSpacer, systemLabel, rightSpacer);
                    container.setStyle("-fx-alignment: center;");
                } else {
                    VBox avatarBox = new VBox(8);
                    avatarBox.setAlignment(javafx.geometry.Pos.TOP_CENTER);
                    
                    if (message.avatar != null) {
                        Image avatarImage = new Image(Objects.requireNonNull(getClass().getResourceAsStream("/org/example/chat/avatar/" + message.avatar)));
                        ImageView avatarView = new ImageView(avatarImage);
                        avatarView.setFitHeight(45);
                        avatarView.setFitWidth(45);
                        avatarView.setPreserveRatio(true);
                        
                        Label nameLabel = new Label(message.sender);
                        nameLabel.setStyle("-fx-font-size: 13px; -fx-text-fill: #666666;");
                        nameLabel.setAlignment(javafx.geometry.Pos.CENTER);
                        
                        avatarBox.getChildren().addAll(avatarView, nameLabel);
                    }

                    VBox contentBox = new VBox(8);
                    contentBox.setAlignment(message.isOwn ? javafx.geometry.Pos.CENTER_RIGHT : javafx.geometry.Pos.CENTER_LEFT);

                    if (message.content.startsWith("IMAGE:")) {
                        String base64Image = message.content.substring(6);
                        byte[] imageData = Base64.getDecoder().decode(base64Image);
                        Image image = new Image(new java.io.ByteArrayInputStream(imageData));
                        ImageView imageView = new ImageView(image);
                        imageView.setFitHeight(200);
                        imageView.setFitWidth(200);
                        imageView.setPreserveRatio(true);
                        contentBox.getChildren().add(imageView);
                    } else {
                        Label messageLabel = new Label(message.content);
                        messageLabel.setPadding(new Insets(15, 20, 15, 20));
                        messageLabel.setWrapText(true);
                        messageLabel.setMaxWidth(280);
                        messageLabel.setStyle(message.isOwn ? 
                            "-fx-background-color: #DCF8C6; -fx-background-radius: 15; -fx-font-size: 15px;" :
                            "-fx-background-color: #FFFFFF; -fx-background-radius: 15; -fx-font-size: 15px;");
                        contentBox.getChildren().add(messageLabel);
                    }

                    if (message.isOwn) {
                        Region spacer = new Region();
                        HBox.setHgrow(spacer, Priority.ALWAYS);
                        container.getChildren().addAll(spacer, contentBox, avatarBox);
                    } else {
                        container.getChildren().addAll(avatarBox, contentBox);
                    }
                }
                setGraphic(container);
            }
        }
    }

    private String getRandomAvatar() {
        // 定义所有可用的头像
        String[] avatars = {"avatar1.jpg", "avatar2.jpg", "avatar3.jpg", "avatar4.jpg", "avatar5.jpg", "avatar6.jpg"};
        
        // 随机选择一个头像
        int randomIndex = new Random().nextInt(avatars.length);
        return avatars[randomIndex];
    }

    private String getUserAvatar(String username) {
        return userAvatars.getOrDefault(username, "avatar1.jpg");
    }
}